# -*- coding:utf-8 -*-
import cv2 as cv
import sys
import numpy as np

if __name__ == '__main__':
    # 读取图像circles.png
    image = cv.imread(r"E:\studylife\detectflaws\code\findFlaws\3.jpg")
    if image is None:
        print('Failed to read circles.png.')
        sys.exit()
    cv.imshow('Origin', image)
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    # 高斯滤波
    gray = cv.GaussianBlur(gray, (9, 9), sigmaX=2, sigmaY=2)

    # 直方图均衡化
    #gray = cv.equalizeHist(gray)  # 普通直方图均衡化
    # clahe = cv.createCLAHE(clipLimit=250, tileGridSize=(2, 2))  # clipLimit：这是对比度限制的阈值
    # gray = clahe.apply(gray)  # tileGridSize：将输入图像划分为M × N块，然后对每个局部块应用直方图均衡化

    # cv.imshow('equal', gray)

    # 计算灰度图的平均灰度值
    average_gray_value = gray.mean()

    # 计算灰度值的中位数
    median_gray_value = np.median(gray)

    # 二值化
    #_, binary = cv.threshold(gray, 250, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    _, binary = cv.threshold(gray, average_gray_value + 10, 255, cv.THRESH_BINARY)

    cv.imshow('binary', binary)

    # 轮廓检测
    contours, hierarchy = cv.findContours(binary, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)

    # 遍历每个轮廓并输出其位置坐标
    nums = 0
    for contour in contours:
        # 获取轮廓的边界框
        x, y, w, h = cv.boundingRect(contour)

        # 输出轮廓的位置坐标 200 > w > 3 and 3 < h < 200
        if 200 > w > 6 and 6 < h < 200:
            nums = nums + 1
            print(f"缺陷{nums}的位置坐标为 ({x}, {y}), 宽度 = {w}, 高度 = {h}")
            image = cv.drawContours(image, [contour], -4, (0, 0, 255), 2, 8)
    print(f"共有{nums}个缺陷")
    # 轮廓绘制
    #image = cv.drawContours(image, contours, -1, (0, 0, 255), 2, 8)

    # 输出轮廓结构关系
    # print(hierarchy)

    # 展示结果
    cv.imshow('Find and Draw Contours', image)
    cv.waitKey(0)
    cv.destroyAllWindows()
